package vip.ola.pay.batchpay.telbatchpay;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Service;
import vip.ola.core.common.constant.PayConstant;
import vip.ola.core.common.util.MyLog;
import vip.ola.core.common.util.PayDigestUtil;
import vip.ola.core.common.util.PayUtil;
import vip.ola.core.entity.AgentpayPassageAccount;
import vip.ola.core.entity.TransOrder;
import vip.ola.pay.channel.BaseTrans;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;

import static vip.ola.core.common.constant.PayEnum.ERR_0121;

/**
 * @author: dingzhiwei
 * @date: 17/12/25
 * @description:
 */
@Service
public class TelpayTransService extends BaseTrans {

    private static final MyLog _log = MyLog.getLog(TelpayTransService.class);

    @Override
    public String getChannelName() {
        return PayConstant.CHANNEL_NAME_ALIPAY;
    }

    public JSONObject trans(TransOrder transOrder) {
        JSONObject retObj = buildRetObj();
        try {
            _log.info("代付转账：" + transOrder.getChannelMchId());
            AgentpayPassageAccount payPassageAccount = rpcCommonService.rpcAgentpayPassageAccountService.findById(transOrder.getPassageAccountId());
            if (payPassageAccount == null || StringUtils.isBlank(payPassageAccount.getParam())) {
                return PayUtil.makeRetFail(ERR_0121);
            }
            JSONObject accountParams = JSONObject.parseObject(payPassageAccount.getParam());
            String mchId = payPassageAccount.getPassageMchId();
            String orderId = transOrder.getTransOrderId();
            String payUrl = accountParams.getString("payUrl");
            String privateKey = accountParams.getString("privateKey");
            BigDecimal amount = new BigDecimal(transOrder.getAmount()).divide(new BigDecimal(100));
            TreeMap<String, String> obj = new TreeMap<String, String>();
            obj.put("bank_name", transOrder.getAccountName().trim());
            obj.put("bank_card", transOrder.getAccountNo().trim());
            obj.put("money", String.valueOf(amount));
            obj.put("mch_id", mchId);
            obj.put("bank_type_name", transOrder.getBankName());
            obj.put("goods_desc", "batch123");
            obj.put("notify_url", accountParams.getString("notify_url"));
            obj.put("order_sn", orderId);
            String time=String.valueOf(System.currentTimeMillis());
            obj.put("time", time);
            obj.put("code","xin");
            obj.put("client_ip", "127.0.0.1");
            obj.put("bank_opening", transOrder.getBankName());
            // 生成签名
            StringBuffer paramstr = new StringBuffer();
            for (String pkey : obj.keySet()) {
                String pvalue = obj.get(pkey);
                if (pvalue != null && pvalue != "") {
                    paramstr.append(pkey + "=" + pvalue + "&");
                }
            }
            String paramsrc = paramstr.substring(0, paramstr.length() - 1);
            String sign = sign(paramsrc,privateKey);
            obj.put("sign", sign);
            _log.info("下单请求url={}，param={},json->{}",payUrl,obj,JSONObject.toJSONString(obj));
            NameValuePair pair = new BasicNameValuePair("mch_id", mchId);
            NameValuePair pair2 = new BasicNameValuePair("bank_name", transOrder.getAccountName().trim());
            NameValuePair pair3 = new BasicNameValuePair("bank_card", transOrder.getAccountNo().trim());
            NameValuePair pair4 = new BasicNameValuePair("money", String.valueOf(amount));
            NameValuePair pair5 = new BasicNameValuePair("bank_type_name", transOrder.getBankName());
            NameValuePair pair6 = new BasicNameValuePair("goods_desc", "batch123");
            NameValuePair pair7 = new BasicNameValuePair("time", time);
            NameValuePair pair8 = new BasicNameValuePair("code", "xin");
            NameValuePair pair9 = new BasicNameValuePair("notify_url", accountParams.getString("notify_url"));
            NameValuePair pair10 = new BasicNameValuePair("order_sn", orderId);
            NameValuePair pair11 = new BasicNameValuePair("client_ip", "127.0.0.1");
            NameValuePair pair12 = new BasicNameValuePair("bank_opening", transOrder.getBankName());
            NameValuePair pair13 = new BasicNameValuePair("sign", sign);
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(16);
            nameValuePairs.add(pair);
            nameValuePairs.add(pair2);
            nameValuePairs.add(pair3);
            nameValuePairs.add(pair4);
            nameValuePairs.add(pair5);
            nameValuePairs.add(pair6);
            nameValuePairs.add(pair7);
            nameValuePairs.add(pair8);
            nameValuePairs.add(pair9);
            nameValuePairs.add(pair10);
            nameValuePairs.add(pair11);
            nameValuePairs.add(pair12);
            nameValuePairs.add(pair13);
            String respData = postWithParamsForString("http://t.hqb72168.com:93/cashout", nameValuePairs);
            _log.info("query end ,the respData->{}",respData);
            _log.info("下单结束respData->{}",respData);
            JSONObject jsonObject = JSONObject.parseObject(respData);
            retObj.put("transOrderId", transOrder.getTransOrderId());
            if (jsonObject != null){
                String code = jsonObject.getString("code");
                if ("1".equals(code)){
                    retObj.put("status",1);
                }else {
                    retObj.put("status",3);
                    retObj.put("channelErrCode", code);
                    retObj.put("channelErrCode", jsonObject.getString("msg"));
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
            retObj.put("status",3);
            retObj.put("channelErrCode", e.getMessage());
        }
        return  retObj;
    }


    public static String postWithParamsForString(String url, List<NameValuePair> params){
        HttpClient client = HttpClients.createDefault();
        HttpPost httpPost =   new HttpPost(url);
        String s = "";
        try {
            httpPost.setEntity(new UrlEncodedFormEntity(params,"UTF-8"));
            httpPost.setHeader("Content-type", "application/x-www-form-urlencoded");
            HttpResponse response = client.execute(httpPost);
            int statusCode = response.getStatusLine().getStatusCode();
            if(statusCode==200){
                HttpEntity entity = response.getEntity();
                s = EntityUtils.toString(entity);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return s;
    }



    private static String sign(String paramSrc, String privateKey) {
        StringBuffer strbuff = new StringBuffer();
        strbuff.append(paramSrc + "&key=" + privateKey);
        String sign = null;
        try {
            sign = PayDigestUtil.md5(strbuff.toString(), "UTF-8");
            _log.info("签名:" + sign);
        } catch (Exception e1) {
            e1.printStackTrace();
        }
        return sign;
    }


    public JSONObject query(TransOrder transOrder) {
//        JSONObject retObj = buildRetObj();
//        retObj.put("transOrderId", transOrder.getTransOrderId());
//        try {
//            Map<String, String> obj = new HashMap<>();
//            obj.put("merchantOrderNo", transOrder.getTransOrderId());
//            String response=callGet("https://pay.fhpay.pro/order/cashierQuery",obj);
//            _log.info("查询结束respData->{}",response);
//            JSONObject jsonObject = JSONObject.parseObject(response);
//            if (jsonObject != null){
//                String code = jsonObject.getString("code");
//                if ("200".equals(code)){
//                    JSONObject dataObject =JSONObject.parseObject(jsonObject.getString("data"));
//                    if (dataObject!= null && "1".equals(dataObject.getString("orderStatus"))){
//                        retObj.put("status", 2);
//                        retObj.put("channelOrderNo", jsonObject.getString("systemOrderNo"));
//                    }else if (dataObject!= null && "0".equals(dataObject.getString("orderStatus"))){
//                        retObj.put("status", 1);
//                        retObj.put("channelOrderNo", jsonObject.getString("systemOrderNo"));
//                    }else if (dataObject!= null && "2".equals(dataObject.getString("orderStatus"))){
//                        retObj.put("status", 3);
//                        retObj.put("channelOrderNo", jsonObject.getString("systemOrderNo"));
//                    }else if (dataObject!= null && "3".equals(dataObject.getString("orderStatus"))){
//                        retObj.put("status", 2);
//                        retObj.put("channelOrderNo", jsonObject.getString("systemOrderNo"));
//                    }else {
//                        retObj.put("status", 1);
//                        retObj.put("channelOrderNo", jsonObject.getString("systemOrderNo"));
//                    }
//                }else {
//                    retObj.put("status", 1);
//                    retObj.put("channelErrCode", code);
//                    retObj.put("channelErrCode", jsonObject.getString("msg"));
//                }
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
        return  null;
    }



    @Override
    public JSONObject balance(String payParam) {
        return null;
    }



}
